var express = require('express');
var router = express.Router();
var ApplicantModel = require('../models/applicant');
var sendMail = require('../models/mailer');
var xss = require('xss');
router.post('/', function(req, res, next) {
    var phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    var mailReg = /^[^\._-][\w\.-]+@([A-Za-z0-9]+\.)+[A-Za-z]+$/;
    var info = req['body'];
    info['name'] = xss(info['name']);
    if (!phoneReg.test(info['phone'])) {
        res.json({ success: false, message: '手机号格式不正确' });
        return;
    }
    if (!mailReg.test(info['email'])) {
        res.json({ success: false, message: '邮箱格式不正确' });
        return;
    }
    ApplicantModel.find({ $or: [{ phone: info['phone'] }, { email: info['email'] }] }, function(err, data) {
        if (data.length === 0) {
            var oneApplicant = new ApplicantModel({ name: info['name'], sex: info['sex'], grade: info['grade'], area: info['area'], department: info['department'], phone: info['phone'], email: info['email'], date: (new Date()), isPayed: 0 });
            oneApplicant.save(function(err, data) {
                if (err) {
                    console.log('error');
                    return err;
                }
                if (data['name']) {
                    sendMail('163', 'zskblognotify@163.com', 'WnmZ197531', info['email'], '武山东老乡会聚餐报名', '恭喜你，报名成功，聚餐时间：10月23日下午5:30，地点：田园小观园');
                    res.json({ success: true, message: '恭喜你，报名成功，邮件已发送！' })
                } else {
                    res.json({ success: false, message: '报名失败，请重试' });
                }
            });
        } else {
            res.json({ success: false, message: '你已报名，请勿重复报名' });
        }
    })


});

module.exports = router;